package com.example.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

@Component
public class MyLoginAuthenticationProvider implements AuthenticationProvider {
//    @Autowired
//    UserDetailsService userDetailsService;
//
//    @Autowired
//    UserDetailsManager userDetailsManager;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//        return "mylogin/authentication";


        MyAuthenticationToken token = (MyAuthenticationToken) authentication;
        token.setAuthenticated(true);
        MyLoginPrincipal principal = (MyLoginPrincipal) token.getPrincipal();

//        userDetailsManager.loadUserByUsername(principal.getUsername());
//        UserDetails userDetails = userDetailsManager.loadUserByUsername(principal.getUsername());
//        if (userDetails == null) {
//            throw new BadCredentialsException("user not found.");
//        }

        MyLoginPrincipal authPrincipal = new MyLoginPrincipal(principal.getUsername(), token.getClientId());


        MyAuthenticationToken authenticationToken = new MyAuthenticationToken(authPrincipal,
                token.getClientId(),
                token.getCredentials().toString(), token.getAuthorities());
        authenticationToken.setAuthenticated(true);

        return token;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return MyAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
